package com.jk1123.us.api.controller;


import com.jk1123.us.api.service.RecordService;
import com.jk1123.us.common.transfer.RadixTransfer;
import com.jk1123.us.common.web.entity.Result;
import com.jk1123.us.common.web.entity.ResultCodeEnum;
import com.jk1123.us.core.ShortUrl;
import com.jk1123.us.core.constant.Constants;
import com.jk1123.us.core.statistics.Statistic;
import com.jk1123.us.core.statistics.StatisticsCollector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2021-09-03 04:01
 * @description
 */
@RestController
@RequestMapping(Constants.URL_CONTROLLER_PATH)
@Slf4j
public class ApiController {
    @Autowired
    private RecordService recordService;
    @Autowired
    private StatisticsCollector statisticsCollector;
    @Autowired
    private RadixTransfer radixTransfer;
    @PostMapping("/")
    public Result generate(
            @RequestParam("longUrl") String longUrl,
            @RequestParam("life") Long life,
            @RequestParam("password") String password
            ){

        ShortUrl shortUrl = new ShortUrl();
        shortUrl.setAppId("100001");
        //shortUrl.set

        recordService.save(shortUrl);

        return Result.successOf();
    }
    @GetMapping("/{shortUrl}")
    public Result query(@PathVariable("shortUrl")String shortUrl){
        if (shortUrl.length()>8){
            return Result.failOf(ResultCodeEnum.USER_ERROR_A0421);
        }
        long num = radixTransfer.string2num(shortUrl);


        ShortUrl su= recordService.findByShort(num);
        statisticsCollector.collect(su, Statistic.create());
        if (su!=null){
            return Result.successOf(su);
        }

        return Result.failOf(ResultCodeEnum.USER_ERROR_A0400);
    }
}
